package com.hlg.xboot.web.interceptor;

import com.hlg.xboot.constants.AppConstants;
import com.hlg.xboot.exceptions.APISignException;
import com.hlg.xboot.exceptions.ParameterException;
import com.hlg.xboot.utils.SecurityUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>Description: API参数签名验证处理</p>
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: 中视数讯</p>
 * <p>Site: www.digi-zones.com</p>
 * <p>myblog: http://blog.csdn.net/xyang81</p>
 *
 * @author 杨信
 * @version 1.0
 * @date 2016/11/1
 */
@Component
public class APISignVerifyInterceptor extends BaseInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        printRequestParams(request);
        if (super.preHandle(request, response, handler)) {
            return true;
        }

        if (!request.getParameterMap().containsKey(AppConstants.PARAM_SIGN_NAME)) {
            throw new ParameterException("无效的签名参数");
        }

        // 签名校验
        String expectSign = SecurityUtils.sign(request.getParameterMap());
        String actualSign = request.getParameter(AppConstants.PARAM_SIGN_NAME);
        logger.debug("expectSign:" + expectSign + ", actualSign:" + actualSign);
        if (!actualSign.equals(expectSign)) {
            throw new APISignException();
        }

        logger.debug("请求参数签名正确.");
        return true;
    }

    @Override
    protected void initExcludeUrls() {
        super.initExcludeUrls();
        addExcludeUrl("*","/wechat/oauth/callback");
        addExcludeUrl("*","/wechat/signature");
    }
}
